package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async //异步执行，另外开现场异步存入
    public CompletableFuture<String> saveTimeLine(Long userId, Long createTime, ObjectId publishId) {
        try {
            //查询该发布用户的id
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> usersList = this.mongoTemplate.find(query, Users.class);
            if (CollUtil.isEmpty(usersList)){
                return CompletableFuture.completedFuture("此用户是孤儿，没有朋友");//这个用户是孤儿，没有朋友
            }
            //依次写入到各个时间线表
            for (Users users : usersList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setDate(createTime);//发布时间
                timeLine.setPublishId(publishId);//发布者ID
                timeLine.setUserId(userId);//好友id
                this.mongoTemplate.save(timeLine,"quanzi_time_line_"+users.getFriendId());//存到朋友的时间线表中
            }
        } catch (Exception e) {
            return CompletableFuture.completedFuture("error");
        }
        return CompletableFuture.completedFuture("ok");
    }
}
